package com.laicunba.ext.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.laicunba.util.CacheUtil;
import com.laicunba.util.SessionUtil;
import com.laicunba.util.StringUtil;

public class CommFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		CacheResponseWrapper wrapper = new CacheResponseWrapper((HttpServletResponse) response);
		chain.doFilter(request, wrapper);
		if (StringUtil.isNotEmpty(SessionUtil.RESPONSE_CACHE_KEY.get())) {
			try {
				String resultTxt = wrapper.getResponseString();
				CacheUtil.setAttribute(SessionUtil.RESPONSE_CACHE_KEY.get(), resultTxt,
						SessionUtil.RESPONSE_CACHE_TIME.get());
			} finally {
				SessionUtil.RESPONSE_CACHE_KEY.remove();
				SessionUtil.RESPONSE_CACHE_TIME.remove();
			}

		}

		// chain.doFilter(request, response);

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
